import { fileURLToPath, URL } from "node:url";
import { createSvgIconsPlugin } from "vite-plugin-svg-icons";
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import AutoImport from 'unplugin-auto-import/vite';
import Icons from "unplugin-icons/vite";
import IconsResolver from "unplugin-icons/resolver";
import Components from 'unplugin-vue-components/vite';
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers';
import path from 'path';
import dts from 'vite-plugin-dts';

export default defineConfig({
  plugins: [
    vue(),
    dts({
      include: ['src/**/*.ts', 'src/**/*.d.ts', 'src/**/*.vue'],
      outDir: 'dist',
      staticImport: true,
      insertTypesEntry: true,
      cleanVueFileName: true,
      copyDtsFiles: true,
    }),
    createSvgIconsPlugin({
      iconDirs: [path.resolve(process.cwd(), "src/assets/svg")],
      symbolId: "i-[dir]-[name]"
    }),
    AutoImport({
      resolvers: [
        IconsResolver({ prefix: "Icon" }),
        ElementPlusResolver()
      ],
    }),
    Components({
      resolvers: [
        IconsResolver({ enabledCollections: ["ep"] }),
        ElementPlusResolver()
      ],
    }),
    Icons({
      autoInstall: true,
      compiler: "vue3"
    }),
  ],
  resolve: {
    alias: {
      "#/": fileURLToPath(new URL("./src", import.meta.url))
    },
  },
  // 核心修正区域
  server: {
    port: 3002, // 插件服务端口（正确）
    host: '0.0.0.0', // 允许外部访问（解决本地网络限制）
    cors: {
      origin: "http://localhost:3000", // 只允许平台（3000端口）跨域访问（更安全）
      methods: ["GET", "POST", "OPTIONS"],
      allowedHeaders: ["*"], // 允许所有请求头
      credentials: true // 允许携带Cookie（如果需要）
    },
    hmr: {
      protocol: 'ws',
      host: 'localhost',
      port: 3002, // 热更新端口必须与插件服务端口一致（关键修正！）
      clientPort: 3000 // 告知HMR客户端连接到平台端口（3000）
    }
  },
  build: {
    outDir: path.resolve(__dirname, './dist'),
    lib: {
      entry: path.resolve(__dirname, 'src/index.ts'),
      formats: ['es']
    },
    rollupOptions: {
      external: ['vue'],
      output: {
        globals: { vue: 'Vue' },
        exports: 'named',
        interop: 'auto'
      }
    },
    minify: true,
    sourcemap: true,
  },
});